package com.bwf.apitest.basic;

import com.alibaba.fastjson2.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class PostTest2 {
    // cookie+表单
    public static void main(String[] args) throws IOException {
        // 1 创建请求
        String uri = "http://172.31.15.54/index.php?m=user&c=user&a=security";
        HttpPost request = new HttpPost(uri);
        // 添加headers
        request.setHeader("Cookie", "PHPSESSID=lunb7eqpq0pothf671419pnjs2; _uname=test29555; user_key=1487Tq6v1qRscLIvKM0wjfr%2FQGNZV9DqPM3wlfffgtAv; cart_num=1");
        request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        request.setHeader("X-Requested-With","XMLHttpRequest");
        // 添加body-entity-json
        String payload = "pwd=" + "123456"
                + "&newpwd=" + "123456"
                + "&newpwd2=" + "123456";
        // 字符串转字符串实体,指定了编码格式
        StringEntity entity = new StringEntity(payload, "UTF-8");
        // 添加实体
        request.setEntity(entity);

        // 2 创建客户端
        CloseableHttpClient client = HttpClients.createDefault();

        // 3 使用客户端发送请求获取响应
        CloseableHttpResponse response = client.execute(request);

        // 4 解析响应结果
        int code = response.getStatusLine().getStatusCode();
        String body = EntityUtils.toString(response.getEntity(), "UTF-8");
        System.out.println(code);
        System.out.println(body);

    }

}
